package module

import (
	"crypto/tls"
	"fmt"
	"github.com/bitly/go-simplejson"
	"io/ioutil"
	"net/http"
	"os/exec"
	"strconv"
	"strings"
)

const token  = "eyJhbGciOiJSUzI1NiIsImtpZCI6IlBobW8ycGtmM1lpSF92Y19kVjBmSFVpeUZXWXlmbnl2d21FdDBNV2FZaWcifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4tbnRzYnciLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMWQxM2Q3ZTMtYTExMC00NTM3LWFmMjUtM2NhZTNhYWI4NGYyIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.EALc1nAvTtjbt0jxMGXw-Ww5UM5YW0YHDEmyfGtcVAtqYAuIqxGRDP67-4K2bh-H9WzGRUDHLDwDOqHxjlNXJfCFbwDhoAr51jbz40ooh9wEvNiEgneY9b-vPL9wxo2rMe7pi_ks4lwhMOvSlOuwmtBElpDNlf_NEW4spTrPPvsgDtEHhxSkyW3ZxsNx-LZzxDiNv5uDCXfqOSXf-PnFInSVdeQhg5ZTQp6JF6G8uoZrSby7nnCXORZGTuoKgSUrNV1Nrg4O3STvil2amypa8JsSMynCnWxR8GZBnBLi03L9a7vHo21myI64JWnKbbEp4hJerU10oGwhVShCpuoESg"
const url  ="https://192.168.0.170:6443/"

func client()  *http.Client{
	client:=&http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}
	return client
}
func SvcFindAll(page Page) SvcPage {
	urls:=url+"api/v1/namespaces/default/services/"
	resp,err:=http.NewRequest("GET",urls,nil)
	if err!=nil{
		fmt.Println(err)
	}
	//resp.Header.Add("Accept", "*/*")
	//resp.Header.Add("Accept-Encoding", "gzip, deflate, br")
	//resp.Header.Set("Access-Control-Allow-Origin","*")
	//resp.Header.Set("Access-Control-Allow-Headers","Content-Type")
	resp.Header.Add("Authorization","Bearer "+token)
	res,_:=client().Do(resp)
	defer res.Body.Close()
	result,_:=ioutil.ReadAll(res.Body)
	//fmt.Println(string(result))
	//解析
	var j *simplejson.Json
	j,_=simplejson.NewJson(result)
	answerNode:=j.Get("items")
	rows,_:=answerNode.Array()
	var s []SvcDescription
	for index,_:=range rows{
		var s1 SvcDescription
		node:=answerNode.GetIndex(index)
		//获取name
		name:=node.Get("metadata").Get("name").MustString()
		s1.Name=name
		//fmt.Println("name",name)
		//获取应用
		svc:=node.Get("spec").Get("selector").Get("app").MustString()
		if svc==""{
			svc=node.Get("spec").Get("selector").Get("name").MustString()
		}
		s1.Svc=svc
		//fmt.Println("svc",svc)
		//获取状态
		stauts:="running"
		s1.Status=stauts
		//fmt.Println("status",stauts)
		//获取创建时间
		time:=node.Get("metadata").Get("creationTimestamp").MustString()
		s1.Time=time
		//fmt.Println("time",time)
		if s1.Name!="kubernetes"{
			s=append(s,s1)
		}
	}
	//分页处理
	//分页处理
	var conPage SvcPage
	conPage.Amount=len(s)
	if page.PageNumber*page.EveryPage>len(s){
		if (page.PageNumber-1)*page.EveryPage>=len(s){
			return conPage
		}else {
			conPage.SD= s[(page.PageNumber-1)*page.EveryPage:]
			return conPage
		}
	}else {
		conPage.SD= s[(page.PageNumber-1)*page.EveryPage:(page.PageNumber-1)*page.EveryPage+page.EveryPage]
		return conPage
		}
}
func SvcFuzzy(fuzzy Fuzzy)  SvcPage{
	urls:=url+"api/v1/namespaces/default/services/"
	resp,err:=http.NewRequest("GET",urls,nil)
	if err!=nil{
		fmt.Println(err)
	}
	//resp.Header.Add("Accept", "*/*")
	//resp.Header.Add("Accept-Encoding", "gzip, deflate, br")
	//resp.Header.Set("Access-Control-Allow-Origin","*")
	//resp.Header.Set("Access-Control-Allow-Headers","Content-Type")
	resp.Header.Add("Authorization","Bearer "+token)
	res,_:=client().Do(resp)
	defer res.Body.Close()
	result,_:=ioutil.ReadAll(res.Body)
	//fmt.Println(string(result))
	//解析
	var j *simplejson.Json
	j,_=simplejson.NewJson(result)
	answerNode:=j.Get("items")
	rows,_:=answerNode.Array()
	var s []SvcDescription
	for index,_:=range rows{
		var s1 SvcDescription
		node:=answerNode.GetIndex(index)
		//获取name
		name:=node.Get("metadata").Get("name").MustString()
		s1.Name=name
		//fmt.Println("name",name)
		//获取应用
		svc:=node.Get("spec").Get("selector").Get("app").MustString()
		if svc==""{
			svc=node.Get("spec").Get("selector").Get("name").MustString()
		}
		s1.Svc=svc
		clusterIp:=node.Get("spec").Get("clusterIP").MustString()
		s1.Clusterip=clusterIp

		port:=node.Get("spec").Get("ports")
		ports,_:=port.Array()
		pt:=""
		for i,_:=range ports{
			p:=port.GetIndex(i)
			pp:=p.Get("port").MustInt()
			pn:=p.Get("nodePort").MustInt()
			ptc:=p.Get("protocol").MustString()
			pt+=strconv.Itoa(pp)+":"+strconv.Itoa(pn)+"/"+ptc+","
		}
		s1.Port=pt[:len(pt)-1]
		//fmt.Println("svc",svc)
		//获取状态
		stauts:="running"
		s1.Status=stauts
		//fmt.Println("status",stauts)
		//获取创建时间
		time:=node.Get("metadata").Get("creationTimestamp").MustString()
		s1.Time=time
		//fmt.Println("time",time)
		//判断名称是否为空
		if s1.Name!="kubernetes"{
			if strings.Contains(s1.Name,fuzzy.Name){
				s=append(s,s1)
			}
		}
	}
	//分页处理
	var conPage SvcPage
	conPage.Amount=len(s)
	if fuzzy.PageNumber*fuzzy.EveryPage>len(s){
		if (fuzzy.PageNumber-1)*fuzzy.EveryPage>=len(s){
			return conPage
		}else {
			conPage.SD= s[(fuzzy.PageNumber-1)*fuzzy.EveryPage:]
			return conPage
		}
	}else {
		conPage.SD= s[(fuzzy.PageNumber-1)*fuzzy.EveryPage:(fuzzy.PageNumber-1)*fuzzy.EveryPage+fuzzy.EveryPage]
		return conPage
	}
}
func SvcFind(name string) SvcDescription {
	urls:=url+"api/v1/namespaces/default/services/"+name
	resp,err:=http.NewRequest("GET",urls,nil)
	if err!=nil{
		fmt.Println(err)
	}
	//resp.Header.Add("Accept", "*/*")
	//resp.Header.Add("Accept-Encoding", "gzip, deflate, br")
	//resp.Header.Add("Access-Control-Allow-Origin","*")
	resp.Header.Add("Authorization","Bearer "+token)
	res,_:=client().Do(resp)
	defer res.Body.Close()
	result,_:=ioutil.ReadAll(res.Body)
	//fmt.Println(string(result))
	//解析
	var j *simplejson.Json
	j,_=simplejson.NewJson(result)
	//answerNode:=j.Get("items")
	var s1 SvcDescription
	node:=j
	//获取name
	nam:=node.Get("metadata").Get("name").MustString()
	s1.Name=nam
	//fmt.Println("name",name)
	//获取应用
	svc:=node.Get("spec").Get("selector").Get("app").MustString()
	if svc==""{
		svc=node.Get("spec").Get("selector").Get("name").MustString()
	}
	s1.Svc=svc
	//fmt.Println("svc",svc)
	//获取状态
	stauts:="running"
	s1.Status=stauts
	//fmt.Println("status",stauts)
	//获取创建时间
	time:=node.Get("metadata").Get("creationTimestamp").MustString()
	s1.Time=time
	//fmt.Println("time",time)
	return s1
}
func SvcDel(name string)error  {
	urls:=url+"api/v1/namespaces/default/services/"+name
	resp,err:=http.NewRequest("DELETE",urls,nil)
	if err!=nil{
		return err
	}
	//resp.Header.Add("Accept", "*/*")
	//resp.Header.Add("Accept-Encoding", "gzip, deflate, br")
	//resp.Header.Add("Access-Control-Allow-Origin","*")
	resp.Header.Add("Authorization","Bearer "+token)
	res,_:=client().Do(resp)
	defer res.Body.Close()
	return nil
}

func SvcCreate(b *http.Request)  error{
	urls:=url+"api/v1/namespaces/default/services/"
	resp,_:=http.NewRequest("POST",urls,b.Body)
	resp.Header.Add("Authorization","Bearer "+token)
	resp.Header.Add("Content-Type","application/yaml")
	res,_:=client().Do(resp)
	defer res.Body.Close()
	return  nil
}

func ConFindAll(page Page) ConPage {
	urls:=url+"apis/apps/v1/namespaces/default/deployments"
	resp,_:=http.NewRequest("GET",urls,nil)
	resp.Header.Add("Authorization","Bearer "+token)
	//resp.Header.Add("Access-Control-Allow-Origin","*")
	//resp.Header.Add("Access-Control-Allow-Headers","Content-Type")
	//resp.Header.Add("content-type","application/json")
	res,_:=client().Do(resp)
	defer res.Body.Close()
	result,_:=ioutil.ReadAll(res.Body)
	var j *simplejson.Json
	j,_=simplejson.NewJson(result)
	answer:=j.Get("items")
	rows,_:=answer.Array()
	var c []ConDescription
	for index,_:=range rows{
		var c1 ConDescription
		node:=answer.GetIndex(index)
		c1.Name=node.Get("metadata").Get("name").MustString()
		img:=node.Get("spec").Get("template").Get("spec").Get("containers")
		imgarry,_:=img.Array()
		immg:=""
		immgName:=""
		for _,_=range imgarry{
			m:=img.GetIndex(0)
			immg=m.Get("image").MustString()
			immgName=m.Get("name").MustString()
		}
		c1.ImageName=immgName
		if strings.Contains(immg,":")==false{
			c1.ImgVersion="latest"
			c1.Image=immg
		}else {
			c1.ImgVersion=strings.Split(immg,":")[1]
			c1.Image=strings.Split(immg,":")[0]
		}
		c1.UsedCount=node.Get("status").Get("availableReplicas").MustInt()
		c1.AllCount=node.Get("status").Get("replicas").MustInt()
		c1.Time=node.Get("metadata").Get("creationTimestamp").MustString()
		if c1.UsedCount!=0{
			c1.Status="running"
		}else {
			c1.Status="stoped"
		}
		c=append(c,c1)
	}
	//分页处理
	var conPage ConPage
	conPage.Amount=len(c)
	if page.PageNumber*page.EveryPage>len(c){
		if (page.PageNumber-1)*page.EveryPage>=len(c){
			return conPage
		}else {
			conPage.CD= c[(page.PageNumber-1)*page.EveryPage:]
			return conPage
		}
	}else {
		conPage.CD=c[(page.PageNumber-1)*page.EveryPage:(page.PageNumber-1)*page.EveryPage+page.EveryPage]
	    return conPage
		}

}
func ConFuzzy(fuzzy Fuzzy)ConPage  {
	urls:=url+"apis/apps/v1/namespaces/default/deployments"
	resp,_:=http.NewRequest("GET",urls,nil)
	resp.Header.Add("Authorization","Bearer "+token)
	//resp.Header.Add("Access-Control-Allow-Origin","*")
	//resp.Header.Add("Access-Control-Allow-Headers","Content-Type")
	//resp.Header.Add("content-type","application/json")
	res,_:=client().Do(resp)
	defer res.Body.Close()
	result,_:=ioutil.ReadAll(res.Body)
	var j *simplejson.Json
	j,_=simplejson.NewJson(result)
	answer:=j.Get("items")
	rows,_:=answer.Array()
	var c []ConDescription
	for index,_:=range rows{
		var c1 ConDescription
		node:=answer.GetIndex(index)
		c1.Name=node.Get("metadata").Get("name").MustString()
		img:=node.Get("spec").Get("template").Get("spec").Get("containers")
		imgarry,_:=img.Array()
		immg:=""
		immgName:=""
		for _,_=range imgarry{
			m:=img.GetIndex(0)
			immg=m.Get("image").MustString()
			immgName=m.Get("name").MustString()
		}
		c1.ImageName=immgName
		if strings.Contains(immg,":")==false{
			c1.ImgVersion="latest"
			c1.Image=immg
		}else {
			c1.ImgVersion=strings.Split(immg,":")[1]
			c1.Image=strings.Split(immg,":")[0]
		}
		c1.UsedCount=node.Get("status").Get("availableReplicas").MustInt()
		c1.AllCount=node.Get("status").Get("replicas").MustInt()
		c1.Time=node.Get("metadata").Get("creationTimestamp").MustString()
		if c1.UsedCount!=0{
			c1.Status="running"
		}else {
			c1.Status="stoped"
		}
		if strings.Contains(c1.Name,fuzzy.Name){
			c=append(c,c1)
		}
	}
	//分页处理
	var conPage ConPage
	conPage.Amount=len(c)
	if fuzzy.PageNumber*fuzzy.EveryPage>len(c){
		if (fuzzy.PageNumber-1)*fuzzy.EveryPage>=len(c){
			return conPage
		}else {
			conPage.CD= c[(fuzzy.PageNumber-1)*fuzzy.EveryPage:]
			return conPage
		}
	}else {
		conPage.CD=c[(fuzzy.PageNumber-1)*fuzzy.EveryPage:(fuzzy.PageNumber-1)*fuzzy.EveryPage+fuzzy.EveryPage]
		return conPage
	}

}
func ConFind(name string)ConDescription  {
	urls:=url+"apis/apps/v1/namespaces/default/deployments/"+name
	resp,_:=http.NewRequest("GET",urls,nil)
	resp.Header.Add("Authorization","Bearer "+token)
	res,_:=client().Do(resp)
	defer res.Body.Close()
	result,_:=ioutil.ReadAll(res.Body)
	var j *simplejson.Json
	j,_=simplejson.NewJson(result)
	node:=j
	var c1 ConDescription
		c1.Name=node.Get("metadata").Get("name").MustString()
		img:=node.Get("spec").Get("template").Get("spec").Get("containers")
		imgarry,_:=img.Array()
		immg:=""
		immgName:=""
		for _,_=range imgarry{
			m:=img.GetIndex(0)
			immg=m.Get("image").MustString()
			immgName=m.Get("name").MustString()
		}
		c1.ImageName=immgName
		if strings.Contains(immg,":")==false{
			c1.ImgVersion="latest"
			c1.Image=immg
		}else {
			c1.ImgVersion=strings.Split(immg,":")[1]
			c1.Image=strings.Split(immg,":")[0]
		}
		c1.UsedCount=node.Get("status").Get("availableReplicas").MustInt()
		c1.AllCount=node.Get("status").Get("replicas").MustInt()
		c1.Time=node.Get("metadata").Get("creationTimestamp").MustString()
		if c1.UsedCount!=0{
			c1.Status="running"
		}else {
			c1.Status="stoped"
		}


	return c1
}

func ConDel(name string)error  {
	urls:=url+"apis/apps/v1/namespaces/default/deployments/"+name
	resp,err:=http.NewRequest("DELETE",urls,nil)
	if err!=nil{
		fmt.Println(err)
	}
	//resp.Header.Add("Accept", "*/*")
	//resp.Header.Add("Accept-Encoding", "gzip, deflate, br")
	//resp.Header.Add("Access-Control-Allow-Origin","*")
	resp.Header.Add("Authorization","Bearer "+token)
	res,_:=client().Do(resp)
	defer res.Body.Close()
	return nil
}

func ConCreate(b *http.Request)error  {
	urls:=url+"apis/apps/v1/namespaces/default/deployments"
	resp,_:=http.NewRequest("POST",urls,b.Body)
	resp.Header.Add("Authorization","Bearer "+token)
	resp.Header.Add("Content-Type","application/yaml")
	res,_:=client().Do(resp)
	defer res.Body.Close()
	return nil
}
func ConReplace(name string,b *http.Request)error  {
	urls:=url+"apis/apps/v1/namespaces/default/deployments/"+name
	resp,_:=http.NewRequest("PUT",urls,b.Body)
	resp.Header.Add("Authorization","Bearer "+token)
	resp.Header.Add("Content-Type","application/yaml")
	res,_:=client().Do(resp)
	defer res.Body.Close()
	return nil
}

func Conreplicas(name string,count string)  error{
	//kubectl sacle deployment deployment-example --replicas=1
	c:="--replicas="+count
	d:="deployment/"+name
		up:=exec.Command("kubectl","scale",c,d)
		if err:=up.Run();err!=nil{
			return err
		}
	return nil
}
func ConVersion(deploymentName string,containerName string,newImg string)  error{
	d:="deployment/"+deploymentName
	c:=containerName+"="+newImg
	up:=exec.Command("kubectl","set","image",d,c)
	if err:=up.Run();err!=nil{
		return err
	}
	return nil
}